package com.rovinj_server.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.PopupMenu;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.rovinj_server.R;
import com.rovinj_server.app.MyApplication;
import com.rovinj_server.db.DBManager;
import com.rovinj_server.fragment.FragmentInventorySaninng;
import com.rovinj_server.fragment.FragmentRecord;
import com.rovinj_server.fragment.InventoryFragment;
import com.rovinj_server.receiver.KeyReceiverListener;
import com.zhy.autolayout.AutoLayoutActivity;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/5/5.
 */

public class TaskActivity extends AutoLayoutActivity implements KeyReceiverListener {

    @Bind(R.id.tob_layout)
    TabLayout mTobLayout;
    @Bind(R.id.view_pager)
    ViewPager mViewPager;
    @Bind(R.id.fh)
    RelativeLayout mFh;
    public int mId;
    @Bind(R.id.rl_jia)
    RelativeLayout mRlJia;
    private InventoryFragment mInventoryFragment;
    private FragmentInventorySaninng mFragmentInventorySaninng;
    private FragmentRecord mFragmentRecord;
    private DBManager mDbManager;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_task);
        ButterKnife.bind(this);
        hidStater();

    }

    @Override
    protected void onStart() {
        super.onStart();
        intiData();
        initViewPager();
    }


    private void intiData() {


        //  mId = (int) intent.getSerializableExtra("id");
        mFragmentInventorySaninng = new FragmentInventorySaninng();
        mInventoryFragment = new InventoryFragment();
        mFragmentRecord = new FragmentRecord();
        //      Bundle bundle = new Bundle();
        //    bundle.putInt("id", mId);
        ///  mFragmentInventorySaninng.setArguments(bundle);
        //  mInventoryFragment.setArguments(bundle);
        //   mFragmentRecord.setArguments(bundle);


    }

    private void initViewPager() {
        mViewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            private String[] titles = new String[]{
                    "盘点扫描", "已盘记录", "提交记录"
            };
            private Fragment[] fragments = new Fragment[]{
                    mFragmentInventorySaninng,
                    mFragmentRecord,
                    mInventoryFragment
            };

            @Override
            public Fragment getItem(int position) {
                return fragments[position];
            }

            @Override
            public int getCount() {
                return titles.length;
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return titles[position];
            }
        });
        mTobLayout.setupWithViewPager(mViewPager);
    }

    /**
     * 隐藏状态栏
     */
    private void hidStater() {
        ActionBar actionBar = getSupportActionBar();
        actionBar.hide();

    }

    @OnClick({R.id.fh, R.id.rl_jia})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.fh:
                if ((System.currentTimeMillis() - exitTime) > 2000) {
                    Toast.makeText(getApplicationContext(), "再按一次退出", Toast.LENGTH_SHORT).show();
                    exitTime = System.currentTimeMillis();
                } else {
                    MyApplication.getInstance().exit();

                }
                break;
            case R.id.rl_jia:
                onPopupButtonClick(mRlJia);

                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                MyApplication.getInstance().exit();

            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public Fragment getVisibleFragment() {
        FragmentManager fragmentManager = TaskActivity.this.getSupportFragmentManager();
        List<Fragment> fragments = fragmentManager.getFragments(); //管理
        for (Fragment fragment : fragments) {
            if (fragment != null && fragment.isVisible())
                return fragment;
        }
        return null;
    }

    @Override
    public void onReceive(final Context context, final Intent intent) {
        //按钮回调事件
        //查询当前显示的页面
        Fragment fragment = getVisibleFragment();
        if (fragment != null && fragment instanceof KeyReceiverListener) {
            final KeyReceiverListener keyReceiverFragment = (KeyReceiverListener) fragment;
            new Thread() {
                @Override
                public void run() {
                    super.run();
                    keyReceiverFragment.onReceive(context, intent);
                }
            }.start();
        }
    }


    private PopupMenu popupMenu;

    //弹出菜单
    public void onPopupButtonClick(View button) {
        final DBManager mDbManager = new DBManager(this);
        mDbManager.copyDBFile();
        //创建PopupMenu对象
        popupMenu = new PopupMenu(this, button);
        //将R.menu.popup_menu菜单资源加载到popup菜单中
        getMenuInflater().inflate(R.menu.task_popup_menu, popupMenu.getMenu());
        //为popup菜单的菜单项单击事件绑定事件监听器
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {

            @Override
            public boolean onMenuItemClick(MenuItem item) {
                if (item.getItemId() == R.id.submit) {
                    final int i = mDbManager.dedeteData(2);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(TaskActivity.this, "清除" + i + "数据", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
                return false;
            }
        });
        popupMenu.show();
    }


}
